<?php

namespace services\clinic;

use Yii;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\clinic\Project;
use common\models\clinic\ProjectBind;
use common\models\clinic\TreatmentRoom;
use api\modules\v1\forms\clinic\TreatmentRoomForm;

/**
 * Class TreatmentRoomService
 * @package services\clinic
 */
class TreatmentRoomService extends Service
{
    /**
     * 根据ID查找治疗室信息
     *
     * @param int $id
     * @return TreatmentRoom|null
     */
    public function findById(int $id = 0): ?TreatmentRoom
    {
        return TreatmentRoom::find()->where(['id' => $id])->one();
    }

    /**
     * 查找治疗室信息
     *
     * @param array $condition
     * @return TreatmentRoom|null
     */
    public function findInfo(array $condition = []): ?TreatmentRoom
    {
        $query = TreatmentRoom::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 治疗室列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = TreatmentRoom::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @return array
     */
    public function findListFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'name' => $row['name'],
            ];
        }

        return $list;
    }

    /**
     * 治疗室列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = TreatmentRoom::find()->select(['a.*', 'GROUP_CONCAT(c.name) AS projetc_names'])->alias('a')
            ->leftJoin(ProjectBind::tableName() . ' AS b', 'b.treatment_room_id = a.id')
            ->leftJoin(Project::tableName() . ' AS c', 'c.id = b.clinic_project_id')
            ->where([
                'a.status' => [TreatmentRoom::STATUS_INVALID, TreatmentRoom::STATUS_ENABLE],
                'a.project_id' => $params['project_id'],
            ])
            ->groupBy('a.id');

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['a.status' => SORT_DESC, 'a.sort' => SORT_ASC])
            ->asArray()
            ->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $projectNamesArr = $row['projetc_names'] ? explode(',', $row['projetc_names']) : [];

            $list[] = [
                'id' => $row['id'],
                'project_id' => $row['project_id'],
                'name' => $row['name'],
                'projetc_names_arr' => $projectNamesArr,
                'status' => $row['status'],
                'status_str' => TreatmentRoom::$statuss[$row['status']],
                'icon_id' => $row['icon_id'],
            ];
        }

        return $list;
    }

    /**
     * 新增治疗室
     *
     * @param TreatmentRoomForm $model
     * @return array|mixed
     */
    public function create(TreatmentRoomForm $model)
    {
        try {
            // 1.新增治疗室
            $role = new TreatmentRoom();
            $role->project_id = $model->project_id;
            $role->name = $model->name;
            $role->status = $model->status;
            $role->icon_id = $model->icon_id;
            $role->save();

            return ['id' => $role->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑治疗室
     *
     * @param TreatmentRoomForm $model
     * @return array|mixed
     */
    public function edit(TreatmentRoomForm $model)
    {
        try {
            // 1.更新治疗室
            $attributes = [
                'name' => $model->name,
                'status' => $model->status,
                'icon_id' => $model->icon_id,
            ];
            TreatmentRoom::updateAll($attributes, ['id' => $model->id]);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 删除治疗室
     *
     * @param TreatmentRoomForm $model
     * @return array|mixed
     */
    public function delete(TreatmentRoomForm $model)
    {
        try {
            // 1.更新治疗室
            $attributes = [
                'status' => TreatmentRoom::STATUS_DELETE,
            ];
            TreatmentRoom::updateAll($attributes, ['id' => $model->id]);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑治疗室状态
     *
     * @param TreatmentRoomForm $model
     * @return array|mixed
     */
    public function editStatus(TreatmentRoomForm $model)
    {
        try {
            // 1.更新治疗室
            $attributes = [
                'status' => $model->status,
            ];
            TreatmentRoom::updateAll($attributes, ['id' => $model->id]);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 绑定治疗项目
     *
     * @param TreatmentRoomForm $model
     * @return array|mixed
     */
    public function bindProject(TreatmentRoomForm $model)
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.删除绑定治疗项目
            ProjectBind::deleteAll([
                'treatment_room_id' => $model->id,
                'clinic_project_id' => $model->getDeleteClinicProjectIds(),
            ]);

            // 2.新增绑定治疗项目
            foreach ($model->getAddClinicProjectIds() as $row) {
                $projectBind = new ProjectBind();
                $projectBind->clinic_project_id = $row;
                $projectBind->treatment_room_id = $model->id;
                $projectBind->save();
            }

            $transaction->commit();

            return ['id' => $model->id];
        } catch (\Exception $e) {
            $transaction->rollBack();

            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 治疗室-治疗项目分组列表
     * @return array
     */
    public static function getRoomProjectList(): array
    {
        $res = Project::find()->alias('p')
            ->select([
                'p.id clinic_project_id', 'p.name projetc_name',
                'pb.treatment_room_id',
                'tr.name room_name', 'tr.status',
            ])
            ->leftJoin(ProjectBind::tableName() . ' pb', 'pb.clinic_project_id = p.id')
            ->leftJoin(TreatmentRoom::tableName() . ' tr', 'tr.id = pb.treatment_room_id')
            ->where([
                'p.project_id' => Yii::$app->params['project_id'],
            ])
            ->orderBy([
                'tr.sort' => SORT_ASC,
                'tr.id' => SORT_ASC,
                'p.sort' => SORT_ASC,
                'p.id' => SORT_ASC,
            ])
            ->asArray()
            ->all();
        $data = [];
        $noRoomData = [];
        $type = 1;// 固定死，前端区分用【1治疗项目、2输液药品】
        foreach ($res as $row) {
            if (empty($row['treatment_room_id'])) {
                $row['treatment_room_id'] = 0;
                $noRoomData[$row['treatment_room_id']] = $noRoomData[$row['treatment_room_id']] ?? [
                    'id' => $row['treatment_room_id'],
                    'name' => '其它组',
                    'child' => [],
                ];
                $noRoomData[$row['treatment_room_id']]['child'][] = [
                    'id' => $row['clinic_project_id'],
                    'name' => $row['projetc_name'],
                    'type' => $type,
                ];
            } else {
                if ($row['status'] != TreatmentRoom::STATUS_ENABLE) {
                    continue;
                }
                $data[$row['treatment_room_id']] = $data[$row['treatment_room_id']] ?? [
                    'id' => $row['treatment_room_id'],
                    'name' => $row['room_name'],
                    'child' => [],
                ];
                $data[$row['treatment_room_id']]['child'][] = [
                    'id' => $row['clinic_project_id'],
                    'name' => $row['projetc_name'],
                    'type' => $type,
                ];
            }
        }
        return array_merge(array_values($data), $noRoomData);
    }
}